import { computed, reactive, ref, toRaw } from 'vue'
import itf from '../utils/interface.js'
import apis, { request } from '../apis/index.js'

const fatalColor = '#DE2E23'
const primaryColor = '#276DE7'

// 删除等主按钮放在左边
async function showReverseModal(config) {
  const res = await itf.showModalSync({
    cancelColor: fatalColor,
    confirmColor: primaryColor,
    ...config,
  })

  return res === false
}

export default function useBoxManager(defaultMode) {
  const mode = ref(defaultMode) // stuffing/unstuffing

  const data = reactive({
    boxCode: new Map(),
    itemCodes: new Map(),
  })

  const boxCode = computed(() => {
    return [...data.boxCode.keys()].join(',')
  })

  const itemCodes = computed(() => {
    return [...data.itemCodes.keys()]
  })

	async function inputResult(code) {
		let codeDetail = {}
		if (mode.value === 'stuffing') {
		  if (!code) throw new Error('请输入箱码或单品码！')
		
		  const stuffingParams = { code }
		
			/* itf.showLoading({
			  title: '加载中',
			}) */
			
			try {
				codeDetail = await request.post(apis.checkCode, stuffingParams)
			} catch (e) {
				throw new Error(e.message)
			} finally {
				itf.hideLoading()
			}
					
			const { displayCode: codeKey } = codeDetail
			switch (codeDetail.codeType) {
					case 'BOXCODE':
						// 箱码逻辑
						// - 如果当前没有箱码，保存新码
						// - 如果当前有箱码（判断是否相同以唯一字段进行比较）
						//   - 当前箱码与新码相同，重新保存一次
						//   - 当前箱码与新码不同，确认后用新码替换旧码
						if (data.boxCode.size && !data.boxCode.get(codeKey)) {
							const confirmReplace = await showReverseModal({
								title: '是否替换箱码',
								content: '您录入了新的箱码，确定替换此前已录入的箱码？',
								cancelText: '替换',
								confirmText: '不替换',
							})
				
							// 未确认替换时，终止后续流程
							if (!confirmReplace) return false
						}
				
						// 为了确保只有一个箱码，每次 set 之前都先清空 map
						data.boxCode.clear()
						data.boxCode.set(codeKey, codeDetail)
				
						return true
					default:
						// 单品码逻辑
						// - 如果存在与新码一致的记录，确认后移除该码（类似多选框反选的逻辑）
						// - 如果不存在与新码一致的记录，添加新码
						if (data.itemCodes.get(codeKey)) {
							const confirmRemove = await showReverseModal({
								title: '是否移除该单品码',
								content: '该单品码已存在，是否将它从本次装箱列表中移除？',
								cancelText: '移除',
								confirmText: '不移除',
							})
				
							// 未确认移除时，终止后续流程
							if (!confirmRemove) return false
				
							data.itemCodes.delete(codeKey)
						} else {
							data.itemCodes.set(codeKey, codeDetail)
						}
				
						return true
				}
		} else if (mode.value === 'unstuffing') {
		  if (!code) throw new Error('请输入箱码！')
		
		  const unstuffingParams = { boxCode: code }
			
			// itf.showLoading({
			//   title: '加载中箱码',
			// })
		
			try {
				codeDetail = await request.post(apis.getBoxItemCodeList, unstuffingParams)
			} catch (e) {
				throw new Error(e.message)
			} finally {
				itf.hideLoading()
			}
		
			const { boxCode, singleCodes = [] } = codeDetail
			data.boxCode.clear()
			data.itemCodes.clear()
			data.boxCode.set(boxCode.displayCode, boxCode)
			singleCodes.forEach(i => {
				data.itemCodes.set(i.displayCode, i)
			})
		
			return true
		} /* else {
		  throw new Error('请检查 mode 值')
		} */
	}

  function input(code) {
		return new Promise(resolve => {
			if (mode.value === 'stuffing') {
				itf.showLoading({
					title: '加载中',
				})
			} else if (mode.value === 'unstuffing') {
				itf.showLoading({
					title: '加载箱码中',
				})
			} else {
				throw new Error('请检查 mode 值')
			}
			
			setTimeout(() => {
				resolve(inputResult(code))
			}, 1000)
		})
  }

  async function removeAllBoxCode() {
    const confirmRemove = await showReverseModal({
      title: '删除箱码',
      content: '您确定要删除已录入的箱码？',
      cancelText: '删除',
      confirmText: '取消',
    })

    if (!confirmRemove) return

    data.boxCode.clear()
  }

  function removeBoxCode(codeKey) {
    data.boxCode.delete(codeKey)
  }

  async function removeAllItemCodes() {
    const confirmRemove = await showReverseModal({
      title: '删除单品码',
      content: '您确定要删除全部单品码？',
      cancelText: '删除',
      confirmText: '取消',
    })

    if (!confirmRemove) return

    data.itemCodes.clear()
  }

  function removeItemCode(codeKey) {
    data.itemCodes.delete(codeKey)
  }

  function importData(newData) {
    data.boxCode = new Map(newData.boxCode)
    data.itemCodes = new Map(newData.itemCodes)
  }

  function exportData() {
    const rawData = toRaw(data)
    return {
      boxCode: [...rawData.boxCode.entries()],
      itemCodes: [...rawData.itemCodes.entries()],
    }
  }

  function exportPureData() {
    const rawData = toRaw(data)
    return {
      boxCode: [...rawData.boxCode.values()],
      itemCodes: [...rawData.itemCodes.values()],
    }
  }

  return reactive({
    boxCode,
    itemCodes,
    input,
    removeAllBoxCode,
    removeBoxCode,
    removeAllItemCodes,
    removeItemCode,
    importData,
    exportData,
    exportPureData,
  })
}
